package com.dongao.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtil {
	private static HttpClient httpClient=null;
//	private HttpResponse httpResponse;
	
	private HttpUtil(){}
	
	/**
	 * 发起http get 请求 并返回请求结果
	 * @return content
	 */
	public static String getUrl(String url) {
		String content = "";
		HttpGet httpGet = new HttpGet(url);
		HttpClient httpClient = getDefaultHttpClient();
		
		InputStream inputStream = null;
		HttpResponse httpResponse = null;
		HttpEntity httpEntity = null;
		
		try {
			httpResponse = httpClient.execute(httpGet);
			httpEntity = httpResponse.getEntity();
			inputStream = httpEntity.getContent();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			String line = "";
			while((line = reader.readLine())!=null) {
				content+=line;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return content;
	}
	
	/**
	 * 发起http post 请求 并返回请求结果
	 * @return content
	 */
	public static String postSubmit(String url, List<NameValuePair> params) {
		String content = "";
		InputStream inputStream = null;
		HttpResponse httpResponse = null;
		HttpEntity httpEntity = null;
		try {
			HttpPost post = new HttpPost(url);
			post.setEntity(httpEntity);
			HttpClient httpClient = getDefaultHttpClient();
			httpResponse = httpClient.execute(post);
			httpEntity = httpResponse.getEntity();
			inputStream = httpEntity.getContent();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			String line = "";
			while((line = reader.readLine())!=null) {
				content+=line;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return content;
	}
	
	private static HttpClient getDefaultHttpClient() {
		if(httpClient==null) {
			httpClient = new DefaultHttpClient();
		}
		
		return httpClient;
	}
}
